package utils

import (
	"crypto/aes"
	"crypto/cipher"
	"fmt"
)

func AesPkcs7Decrypt(encryptedMsg, AESKey, iv []byte) ([]byte, error) {
	BLOCK_SIZE := 32 // PKCS#7
	if len(encryptedMsg) < BLOCK_SIZE {
		err := fmt.Errorf("the length of encryptedMsg too short: %d", len(encryptedMsg))
		return nil, err
	}
	// if len(encryptedMsg)%BLOCK_SIZE != 0 {
	// 	err := fmt.Errorf("encryptedMsg is not a multiple of the block size, the length is %d", len(encryptedMsg))
	// 	return nil, err
	// }
	plain := make([]byte, len(encryptedMsg)) // len(plain) >= BLOCK_SIZE
	// 解密
	block, err := aes.NewCipher(AESKey[:])
	if err != nil {
		return nil, err
	}
	if iv == nil {
		iv = AESKey[:16]
	}
	mode := cipher.NewCBCDecrypter(block, iv)
	mode.CryptBlocks(plain, encryptedMsg)
	// PKCS#7 去除补位
	amountToPad := int(plain[len(plain)-1])
	//if amountToPad < 1 || amountToPad > BLOCK_SIZE {
	//	err := fmt.Errorf("the amount to pad is invalid: %d", amountToPad)
	//	return nil, err
	//}
	plain = plain[:len(plain)-amountToPad]
	return plain, nil
}
